﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class TileMonoBehaviour : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public bool isWalkable;
    public bool isOcupied;
    public bool isCurrent = false;
    public bool isTarget = false;
    public bool isSelectable = false;

    public bool isCalculatePath = false;
    public bool isSetPath = false;

    public float jumpHeight = 1f;

    public List<TileMonoBehaviour> adjacencyList = new List<TileMonoBehaviour>();

    public int turnCounter = -1;

    // BFC config

    public bool isVisited = false;
    public TileMonoBehaviour parentTile = null;
    public int distance = 0;

    // A* Config
    public float f = 0; // f = g + h
    public float g = 0;
    public float h = 0;

    private SpriteRenderer spriteRenderer;
    private Collider2D currentCollider;

    [Header("分数信息")] private readonly int defaultScore = StaticDataManager.SCORE_WITHOUT_COVER;
    [SerializeField]
    private int currentScore = 0;

    public void ResetParam()
    {
        isWalkable = true;
        isCurrent = false;
        isTarget = false;
        isSelectable = false;

        isVisited = false;
        parentTile = null;
        distance = 0;

        isSetPath = false;
        isCalculatePath = false;

        adjacencyList.Clear();

        f = g = h = 0;
    }

    public void FindNeighbors(TileMonoBehaviour targetTile)
    {
        ResetParam();

        float checkDistance = 1f;
        
        CheckTile(Vector2.up, checkDistance, targetTile);
        CheckTile(Vector2.down, checkDistance, targetTile);
        CheckTile(Vector2.left, checkDistance, targetTile);
        CheckTile(Vector2.right,checkDistance, targetTile); 
    }

    public void CheckTile(Vector2 direction, float checkDistance, TileMonoBehaviour targetTile)
    {
        RaycastHit2D[] results = new RaycastHit2D[1];
        Physics2D.RaycastNonAlloc(transform.position, direction, results, checkDistance);
        foreach (var hit in results)
        {
            if (hit)
            {
                TileMonoBehaviour tile = hit.collider.GetComponent<TileMonoBehaviour>();
                if (tile && ((tile == targetTile) || !tile.isOcupied))
                {
                    adjacencyList.Add(tile);
                }
            }   
        }
    }

    public void ResetScore()
    {
        currentScore = defaultScore;
    }

    public void AddScore(int score)
    {
        currentScore += score;
    }

    public int GetScore()
    {
        return currentScore;
    }

    public int GetCurrentScore()
    {
        return currentScore;
    }

    public void FreshScoreNumberSprite(bool isForce = false)
    {
        ValueTuple<Sprite, Color> numberSpriteColorPair = GameObject.FindGameObjectWithTag(StaticDataManager.GAME_SESSION_TAG).GetComponent<GameSession>().GetNumberSprite(currentScore);
        transform.GetChild(0).GetComponent<SpriteRenderer>().sprite = numberSpriteColorPair.Item1;
        transform.GetChild(0).GetComponent<SpriteRenderer>().color = numberSpriteColorPair.Item2;
    }

    void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        currentCollider = GetComponent<Collider2D>();

        adjacencyList = new List<TileMonoBehaviour>();

        SetTileColorByStatus();
    }

    private void Update()
    {
        //SetTileColor();
    }

    public void unDisplay()
    {
        spriteRenderer.enabled = false;

    }

    public void Display()
    {
        spriteRenderer.enabled = true;
    }

    public void SetTileColor(Color color)
    {
        spriteRenderer.color = color;
    }
    
    public void SetTileColorByStatus()
    {
        Color changeColor = Color.clear;
        changeColor.a = 0f;
        
        if ((isSelectable || isSetPath || isTarget))
        {
            changeColor.a = 1f;
            changeColor = Color.green;
        }

        if (changeColor != spriteRenderer.color)
        {
            spriteRenderer.color = changeColor;
        }
    }

    private void OnDrawGizmosSelected()
    {
        RaycastHit2D[] results = new RaycastHit2D[1];
        foreach (Vector2 direction in new Vector2[] { Vector2.up, Vector2.down, Vector2.left, Vector2.right })
        {
            Physics2D.RaycastNonAlloc(transform.position, direction, results, 0.7f, LayerMask.GetMask(StaticDataManager.BLOCK_LAYER));

            if (!results[0].collider) continue;
            
            GameObject target = results[0].collider.gameObject;

            Gizmos.color = Color.cyan;
            Gizmos.DrawLine(transform.position, target.transform.position);
        }
    }
    
    #region 鼠标悬停事件
    public void OnPointerEnter(PointerEventData eventData)
    {
//        Debug.Log("Enter");
        GameObject.FindGameObjectWithTag(StaticDataManager.SELECTED_GRID_TAG).transform.position = this.gameObject.transform.position;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
//        Debug.Log("Exit");
//        GameObject.FindGameObjectWithTag(StaticDataManager.SELECTED_GRID_TAG).transform.position = Vector3.zero;
    }
    #endregion
}
